﻿using System.Drawing;
using System.Windows.Forms;
using CanvasControl.Interface;
using CanvasControl.Model;
using GraphDrawing.Graph.Model;

namespace GraphDrawing.Graph.Behaviors
{
    public class CanvasEventsListener : IInputListener
    {
        readonly ModelStateContext context;

        ModelStatePresenter state = IdleState.INSTANCE;

        public CanvasEventsListener(ModelStateContext context)
        {
            this.context = context;
        }

        public void OnMouseDown(InputState input)
        {
            state = DispatchState(input);
        }

        public void OnMouseUp(Point p)
        {
            state.OnMouseUp(p);
            state = IdleState.INSTANCE;
        }

        public void OnMouseMove(Point p)
        {
            state.OnMouseMove(p);
        }

        ModelStatePresenter DispatchState(InputState input)
        {
            if (input.MouseButtons == MouseButtons.Right)
                return new ViewPortMovingState(context, input.ClientPoint);

            var viewport = context.CanvasModel.ViewPort;
            var hitTest = context.Graph.HitTest(input.ViewPoint, viewport.IsVisible);
            switch (hitTest.hitType)
            {
                case HitType.BLOCK:
                    return new DraggingStatePresenter(context, input.ViewPoint, hitTest.block);
                case HitType.SLOT:
                    return new LinkingStatePresenter(context, hitTest.slot);
                case HitType.CONNECTION:
                    return new ConnectionSelectionState(context, input.ViewPoint, hitTest.connection);
                default:
                    context.Graph.ClearSelection();
                    return new SelectionBoxStatePresenter(context, input.ViewPoint);
            }
        }
    }
}
